<template>
  <CenterBase>
    <template #CenterBase>
      <div style="text-align: center; margin-top: 20px">
        <h1>修改信息</h1>
      </div>
      <div style="margin-top: 50px">
        <a-form>
          <a-form-item label="邮&emsp;&emsp;箱&emsp;" name="email" v-if="!modifyMode">
            <a-input v-model:value="formData.email"/>
          </a-form-item>
          <a-form-item label="当前用户名" name="oldName" v-if="modifyMode">
            <a-input v-model:value="oldName" :disabled="true" />
          </a-form-item>
          <a-form-item label="新用户名&emsp;" name="username" v-if="modifyMode">
            <a-input v-model:value="formData.username" @blur="checkUserName" />
          </a-form-item>
          <a-form-item label="新密码&emsp;&emsp;" name="passwd" v-if="!modifyMode">
            <a-input-password v-model:value="formData.passwd" />
          </a-form-item>
          <a-form-item label="确认新密码" name="confirm" v-if="!modifyMode">
            <a-input-password v-model:value="formData.confirm" />
          </a-form-item>
          <a-form-item label="验证码&emsp;&emsp;" name="validCode" v-if="!modifyMode">
            <a-input v-model:value="formData.validCode" placeholder="系统会向你的注册邮箱发送验证码(可能在垃圾箱中)"/>
          </a-form-item>
          <a-form-item>
            <span v-if="!modifyMode">邮件服务，请不要疯狂请求，请求多了会被封，拜托了。验证码邮件可能出现在垃圾箱或者广告分类中，请注意查找。</span>
            <span v-if="modifyMode">用户名修改后，因为前端缓存，可能不能及时更新！第二天会自动刷新。</span>
          </a-form-item>
          <a-form-item>
            <a-button type="primary" ghost @click.stop="fetchValidCode" v-if="!modifyMode"> <loading-outlined v-show="isLoading"/>发送验证码</a-button>
            <a-button type="primary" style="margin-left: 40px" @click.stop="submitModify">提交修改</a-button>
          </a-form-item>
        </a-form>
      </div>
    </template>
  </CenterBase>
  <Footer />
</template>

<script lang="ts">
import { defineComponent, reactive, ref, onMounted } from 'vue'
import Footer from '@/components/Footer.vue'
import { Input, Form, Button, message } from 'ant-design-vue'
import CenterBase from '@/components/CenterBase.vue'
import {
  checkRegisterField, getValidCode, resetName, resetPasswd
} from '@/service'
import { RestPass } from '@/utils/ds'
import { useRouter, useRoute } from 'vue-router'
import { LoadingOutlined } from '@ant-design/icons-vue'
import { getUserName, setCacheLong, setCache } from '@/utils/common'
import { checkToken } from '@/utils/check'
import { userName } from '@/utils/constants'

export default defineComponent({
  name: 'ModifyInfo',
  components: {
    Footer,
    CenterBase,
    LoadingOutlined,
    AInput: Input,
    AInputPassword: Input.Password,
    AForm: Form,
    AFormItem: Form.Item,
    AButton: Button
  },
  setup () {
    const lastReqTime = ref<number>(0)
    const isLoading = ref<boolean>(false)
    const router = useRouter()
    const route = useRoute()
    const formData = reactive({
      email: '',
      username: '',
      passwd: '',
      confirm: '',
      validCode: ''
    })
    const oldName = ref<string>('')
    const modifyMode = ref<boolean>(false)
    const submitModify = () => {
      if (modifyMode.value) {
        // 修改用户名
        if (formData.username.length === 0) {
          message.info('新用户名为空')
          return
        }
        if (formData.username.length > 15) {
          message.info('新用户名太长了')
          return
        }
        const token = checkToken()
        resetName(formData.username, token)
          .then((response) => {
            if (response.status !== 200) {
              message.info('请求出错')
              return
            }
            const resp = response.data
            if (resp.code === 0 && resp.data === true) {
              message.info('修改成功')
              setCache(userName, formData.username)
              setCacheLong(userName, formData.username)
            } else {
              message.info('修改失败')
            }
          })
      } else {
        if (formData.email.length === 0) {
          message.warn('请填入邮箱地址')
          return
        }
        if (formData.passwd.length === 0) {
          message.warn('新密码为空')
          return
        }
        if (formData.passwd.length < 8 || formData.passwd.length > 20) {
          message.info('密码长度在8~20位')
          return
        }
        if (formData.confirm.length === 0) {
          message.warn('确认密码为空')
          return
        }
        if (formData.passwd !== formData.confirm) {
          message.warn('重置密码与确认密码不相等')
          return
        }
        if (formData.validCode.length === 0) {
          message.warn('验证码为空，请点击【发送验证码】按钮获取验证码')
          return
        }
        const sendData: RestPass = {
          email: formData.email,
          passwd: formData.passwd,
          validCode: formData.validCode
        }
        resetPasswd(sendData)
          .then((response) => {
            if (response.status !== 200) {
              message.error('请求出错', 0.5)
              return
            }
            const resp = response.data
            if (resp.code === 0) {
              message.info('重置密码成功')
              setTimeout(() => {
                router.replace('/login')
              }, 250)
            }
          })
        // 修改新密码
      }
    }

    const fetchValidCode = () => {
      const cur = Math.floor(new Date().getTime() / 1000)
      if (lastReqTime.value !== 0) {
        if (cur > lastReqTime.value && cur - lastReqTime.value <= 1800) {
          message.info('验证码30分钟内有效，可使用刚刚发送的验证码')
          return
        }
      }
      lastReqTime.value = cur
      if (formData.email.length === 0) {
        message.warn('请填入邮箱地址')
        return
      }
      isLoading.value = true
      getValidCode(formData.email)
        .then((response) => {
          if (response.status !== 200) {
            return
          }
          const resp = response.data
          if (resp.code === 1003) {
            message.info('验证码还在有有效期，请使用刚刚发送的验证码')
            return
          }
          if (resp.code === 1004) {
            message.error('获取验证码失败')
            return
          }
          if (resp.code === 0) {
            message.info('验证码已发送，30分钟内有效')
          }
          isLoading.value = false
        })
        .catch(() => {
          isLoading.value = false
        })
    }

    const checkUserName = async () => {
      const newName = formData.username
      if (newName.length <= 0) {
        return
      }
      const data = new Map<string, string>()
      data.set('f', 'name')
      data.set('v', newName)
      const ret = await checkRegisterField(data)
      if (ret.status === 200) {
        const d = ret.data
        if (d.data === true) {
          message.info('该名字已经存在', 0.5)
        }
      }
    }

    onMounted(() => {
      const mode = route.params.mode as string
      console.log(mode)
      if (mode === '1') {
        modifyMode.value = true
      } else if (mode === '0') {
        modifyMode.value = false
      }
      oldName.value = getUserName()
    })

    return {
      oldName,
      modifyMode,
      formData,
      isLoading,
      checkUserName,
      submitModify,
      fetchValidCode
    }
  }
})
</script>

<style scoped>

</style>
